package com.hr.utils;

import io.jsonwebtoken.*;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.security.Key;
import java.util.Base64;
import java.util.Date;

import javax.crypto.spec.SecretKeySpec;
import java.util.Map;

@Component
public class JwtUtils {

    @Value("${jwt.secret-base64}")
    private String secretBase64;

    @Value("${jwt.expire-time}")
    private long expirationTime;

    private static String SECRET_BASE64;
    private static long EXPIRATION_TIME;


    // 将 Base64 密钥转为 Key 对象（只初始化一次）
    /*private static Key CreatSigningKey() {
        // 解码密钥字符串
        byte[] decodedKey = java.util.Base64.getDecoder().decode(SECRET_BASE64);
        // 生成密钥对象
        return new SecretKeySpec(decodedKey, "HmacSHA256");
    }
    */
    private static Key SIGNING_KEY;

    @PostConstruct
    public void init() {
        SECRET_BASE64 = secretBase64;
        EXPIRATION_TIME = expirationTime;
        // 初始化签名密钥
        byte[] decodedKey = Base64.getDecoder().decode(SECRET_BASE64);
        SIGNING_KEY = new SecretKeySpec(decodedKey, "HmacSHA256");
    }


    /*//设置签名密钥
    private static final String SECRET_STRING = "hr-service";
    //设置token过期时间为12小时
    private static final long EXPIRATION_TIME = 12 * 60 * 60 * 1000;*/

    /**
     * 生成token
     * @param claims
     * @return
     */
    public static String generateJwt(Map<String, Object> claims) {
        return Jwts.builder()
                .addClaims(claims)
                .signWith(SignatureAlgorithm.HS256, SIGNING_KEY)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .compact();
    }

    /**
     * 解析token
     * @param jwt
     * @return
     */
    public static Claims parseJwt(String jwt) {
        try {
            return Jwts.parser()
                    .setSigningKey(SIGNING_KEY)
                    .parseClaimsJws(jwt)
                    .getBody();
        }catch (ExpiredJwtException e){
            throw new RuntimeException("Token已过期", e);
        }catch (MalformedJwtException e){
            throw new RuntimeException("Token格式错误", e);
        }catch (IllegalArgumentException e){
            throw new RuntimeException("Token为空", e);
        }
    }
    /**
     * 验证token是否过期
     * @param jwt
     * @return
     */
    public static boolean isTokenExpired(String jwt) {
        if (jwt == null || jwt.trim().isEmpty()) {
            return true;
        }
        try {
            Claims claims = parseJwt(jwt);//解析token
            Date expiration = claims.getExpiration();//获取token的过期时间
            return expiration.before(new Date());//判断当前时间是否在过期时间之前
        } catch (Exception e) {//如果解析失败，则返回true表示token已过期
            return true;//token已过期
        }
    }

}
